package data

import (
	"eag_arch_layout/internal/model/VO"
	"eag_arch_layout/internal/model/model"
	"eag_arch_layout/internal/svc"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"strings"
)

type accountRepo struct {
	b   *BaseRepo
	log *log.Helper
}

// NewAccountRepo .
func NewAccountRepo(data *BaseRepo, logger log.Logger) svc.AccountRepo {
	return &accountRepo{
		b:   data,
		log: log.NewHelper(logger),
	}
}

func (a *accountRepo) GetPager(searchModel *VO.PageSearchModel) ([]*model.VAccountInfo, int64) {
	//TODO implement me
	//panic("implement me")
	para := searchModel.GetSearchParam()
	var whereSql []string
	var params []interface{}
	if v, ok := para["loginID"]; ok && len(v.(string)) > 0 {
		whereSql = append(whereSql, "loginID LIKE ?")
		params = append(params, fmt.Sprintf("%%%s%%", v))
	}
	if v, ok := para["nickName"]; ok && len(v.(string)) > 0 {
		whereSql = append(whereSql, "nickName LIKE ?")
		params = append(params, fmt.Sprintf("%%%s%%", v))
	}
	if v, ok := para["email"]; ok && len(v.(string)) > 0 {
		whereSql = append(whereSql, "email LIKE ?")
		params = append(params, fmt.Sprintf("%%%s%%", v))
	}
	if v, ok := para["moblie"]; ok && len(v.(string)) > 0 {
		whereSql = append(whereSql, "moblie LIKE ?")
		params = append(params, fmt.Sprintf("%%%s%%", v))
	}
	vSql := " select * from v_account_info where isnull(isDelete,0)= 0 "
	searchModel.Order = " id "
	// 1 调用 BaseRepo
	return Pager[model.VAccountInfo](*a.b, vSql, whereSql, params, searchModel)

	// 2 自己构建
	//var row []*v1.UserPageReply_Rows
	//a.b.db.Table("v_account_info").Where(sb.String()).Offset(searchModel.Offset).Limit(searchModel.Limit).Find(&row)
	//var allRows int //查询到的总记录数
	//a.b.db.Raw("SELECT count(1) FROM v_account_info WHERE " + sb.String()).Scan(&allRows)

	// 3.method
	//var rows []*v1.UserPageReply_Rows
	//whereSqlStr := strings.Join(whereSql, " AND ")
	//if len(whereSqlStr) > 0 {
	//	whereSqlStr = " WHERE " + whereSqlStr
	//}
	//vSql1 := fmt.Sprintf("SELECT * FROM (%s) AS t %s", vSql, whereSqlStr)
	//a.b.db.Scan(vSql1).Where("", para).Offset(searchModel.Offset).Limit(searchModel.Limit).Find(&rows)
	//var allRows int //查询到的总记录数
	//vSql2 := fmt.Sprintf("SELECT count(1) FROM (%s) AS t %s", vSql, whereSqlStr)
	//a.b.db.Raw(vSql2).Where("", para).Scan(&allRows)
	//return &v1.UserPageReply{
	//	Rows:       rows,
	//	TotalCount: allRows,
	//	PageIndex:  int64(searchModel.PageIndex),
	//	PageSize:   int64(searchModel.Limit),
	//}, nil
}

func (a *accountRepo) LockOrNot(id string) bool {
	vSql := `update SYS_ACCOUNT SET isLock = (case when isnull(isLock,0)=1 then 0 else 1 end)
			where loginID = ?`
	tx := a.b.db.Exec(vSql, id)
	return tx.RowsAffected > 0
}

func (a *accountRepo) ChkBeforeSave(po *model.SysAccount) bool {
	//TODO implement me
	var whereSql []string
	var para []interface{}
	whereSql = append(whereSql, " loginID = ? ")
	para = append(para, po.LoginID)
	if po.ID > 0 { // 修改
		whereSql = append(whereSql, " id <> ? ")
		para = append(para, po.ID)
	}
	var count int64
	a.b.db.Table("SYS_ACCOUNT").Where(strings.Join(whereSql, " AND "), para...).Count(&count)
	return count == 0
}

func (a *accountRepo) Save(po *model.SysAccount) bool {

	if po.ID > 0 {
		result := a.b.db.Model(&po).Omit("id", "password", "creatorID", "isLock", "isDelete", "createdTime").Updates(po)
		return result.RowsAffected > 0
	} else {
		result := a.b.db.Omit("updatorID", "isLock", "isDelete", "updatedTime").Create(&po)
		return result.RowsAffected > 0
	}
}

func (a *accountRepo) Delete(idArray []string) error {

	a.b.db.Model(&model.SysAccount{}).Where("loginID in ?", idArray).Update("isDelete", 1)
	return nil
}

// FindByLoginID 根据登录ID查询账号
func (a *accountRepo) FindByLoginID(loginId string) (*model.VAccountInfo, error) {
	var result *model.VAccountInfo
	a.b.db.Where("loginID = ?", loginId).First(&result)
	return result, nil
}

// GetPwdHashByLoginID 根据登录ID查询密码哈希
func (a *accountRepo) GetPwdHashByLoginID(loginId string) (string, error) {
	account, err := a.FindByLoginID(loginId)
	if err != nil {
		return "", err
	}
	if account != nil {
		return account.Password, nil
	}
	return "", nil
}

// ChangePassword 修改密码
func (a *accountRepo) ChangePassword(loginIdArray []string, newPwdHash string) bool {
	tx := a.b.db.Table("SYS_ACCOUNT").Where("loginID in ?", loginIdArray).Update("Password", newPwdHash)
	return tx.RowsAffected > 0
}
